﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Cultivos;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.Core.Entities;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Cultivos
{
	public partial class CultivosViewModel
	{
		#region Private properties

		/// <summary>
		/// Lista de cultivos.
		/// </summary>
		private List<Cultivo> _cultivos;

		/// <summary>
		/// Cultivo actualmente seleccionado.
		/// </summary>
		private Cultivo _cultivo;

		#endregion

		#region Public properties

		/// <summary>
		/// Lista de cultivos.
		/// </summary>
		public List<Cultivo> Cultivos
		{
			get
			{
				return _cultivos;
			}
			private set
			{
				_cultivos = value;
				if (_cultivos != null)
					RaisePropertyChanged("Cultivos");
			}
		}

		/// <summary>
		/// Cultivo actualmente seleccionado en la vista.
		/// </summary>
		public Cultivo Cultivo
		{
			get
			{
				return _cultivo;
			}
			private set
			{
				_cultivo = value;
				if (_cultivo != null)
					RaisePropertyChanged("Cultivo");
			}
		}

		/// <summary>
		/// Identifica si ya se seleccionó un cultivo.
		/// </summary>
		public bool IsCultivoReady
		{
			get
			{
				return Cultivo != null;
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// Carga todos los cultivos.
		/// </summary>
		private void LoadCultivos()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					ICultivoService service = IoCFactory.Resolve<ICultivoService>();
					e.Result = service.FindAllCultivos();
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Cultivos = e.Result as List<Cultivo>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// Envía los cambios realizados a los cultivos.
		/// </summary>
		private void SaveCultivos(object s, EventArgs args)
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					ICultivoService service = IoCFactory.Resolve<ICultivoService>();
					Cultivos.ForEach(c =>
					{
						if (c.ChangeTracker.State == ObjectState.Added)
							service.AddCultivo(c);
						else if (c.ChangeTracker.State == ObjectState.Modified)
							service.ChangeCultivo(c);
						c.AcceptChanges();
					});
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						LoadCultivos();
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		/// <summary>
		/// Ocurre al agregar un nuevo cultivo.
		/// </summary>
		private void AddNewCultivo(object sender, EventArgs e)
		{
			_view.cultivosBindingSource.AddingNew += AddingNewCultivo;
			_view.cultivosBindingSource.AddNew();
		}

		/// <summary>
		/// Ocurre al momento de estar siendo agregado un nuevo cultivo.
		/// </summary>
		/// <remarks>
		/// En éste evento se asignan los valores por defecto si es necesario.
		/// </remarks>
		private void AddingNewCultivo(object sender, AddingNewEventArgs e)
		{
			Cultivo = new Cultivo
			{
				ClasificacionGuid = Guid.Empty,
				ClasificacionId = 0,
				CultivoGuid = Guid.NewGuid(),
				CultivoId = 0,
				EstacionGuid = Guid.Empty,
				EstacionId = 0,
				Nombre = string.Empty,
				Status = true,
			};
			Cultivo.MarkAsAdded();
			e.NewObject = Cultivo;
			FocusDefaultControl();
		}

		/// <summary>
		/// 
		/// </summary>
		private void SetCurrentCultivo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null && bindingSource.Current != null)
				Cultivo = bindingSource.Current as Cultivo;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnCultivosPropertyChanged()
		{
			_view.cultivosBindingSource.DataSource = Cultivos;
			_view.cultivosBindingSource.CurrentChanged += SetCurrentCultivo;
			SetCurrentCultivo(_view.cultivosBindingSource, new EventArgs());
		}

		private void OnCultivoPropertyChanged()
		{
			Cultivo.MarkAsModified();
		}

		#endregion

	}
}
